import atexit
import fcntl
from apps.jobs.context import GlobalContext
from flask_apscheduler import APScheduler
from apps.jobs.settings import config

if config.SERVER_ENV != 'dev':
    from gevent import monkey
    
    monkey.patch_all()
else:
    pass

from apps.jobs.views.jobs import jobs
from library.api.tFlask import tflask, register_logger

context_scheduler = None


def create_app():
    app = tflask(config)
    register_blueprints(app)
    register_logger(app, config)
    scheduler_lock(app)
    return app


def scheduler_lock(app):
    f = open("scheduler.lock", "wb")
    try:
        fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
        scheduler = APScheduler()
        scheduler.init_app(app)
        scheduler.start()
        GlobalContext.set_context(scheduler)
    except:
        pass
    
    def unlock():
        fcntl.flock(f, fcntl.LOCK_UN)
        f.close()
        GlobalContext.set_context(None)
    
    atexit.register(unlock)


def register_blueprints(app):
    app.register_blueprint(jobs, url_prefix="/v1/jobs")


if __name__ == '__main__':
    create_app().run(port=config.PORT, server_env=config.SERVER_ENV)
